package alvarodelrosal.chat.server.modelo;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.util.LinkedList;
import java.util.List;

public class ChatServer {

    private static boolean stop = false;
    private static List<ChatConnection> connections = new LinkedList();
    private static final Object lock = new Object();

    public static void main(String args[]) throws IOException {
        Socket client = null;

        try {
            ServerSocket server = new ServerSocket(9999);
            server.setSoTimeout(3000);

            while (!stop) {
                try {
                    client = server.accept();
                    ChatConnection connection = new ChatConnection(client);
                    connection.start();
                    connections.add(connection);
                } catch (SocketTimeoutException e) {
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static List<ChatConnection> onlineUsers() {
        return connections;
    }

    public static ChatConnection getUser(int user) {
        synchronized (lock) {
            for (ChatConnection connection : connections) {
                if (connection.whoAmI().getUserId() == user) {
                    return connection;
                }
            }
            return null;
        }
    }

    public static void removeConnection(ChatConnection connection) {
        synchronized (lock) {
            connections.remove(connection);
        }
    }
}
